import React, { useEffect, useState } from 'react';
import { getMaterial, editMaterial, addMaterial, delMaterial, getSearch } from '../../api/material';
import 'video-react/dist/video-react.css';
import { Player } from 'video-react';
import {
    Space,
    Tag,
    Button,
    Form,
    Input,
    Popconfirm,
    Table,
    Modal,
    Image,
    Upload,
    message
} from 'antd';
import { UploadOutlined, PlusOutlined } from '@ant-design/icons';
const { CheckableTag } = Tag;
const { TextArea, Search } = Input;
const tagsData = [
    { title: '影视剧', type: 1 },
    { title: '剧本', type: 0 },
    { title: '动漫', type: 2 },
    { title: '合拍', type: 4 },
];

const Material = () => {
    const [data, setData] = useState([]);
    const [selectedTag, setSelectedTag] = useState('影视剧');
    const [type, setType] = useState(1)
    // 分页
    const [total, setTotal] = useState(0);
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    // 表格
    const [form] = Form.useForm();
    // 梗概对话框
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [defaultValue, setDefaultValue] = useState('');
    // 视频对话框
    const [isVideoOpen, setIsVideoOpen] = useState(false);
    const [videoMsg, setVideoMsg] = useState('');
    // 编辑对话框
    const [isEditOpen, setIsEditOpen] = useState(false);
    const [msg, setMsg] = useState('');
    // 新建数据框
    const [isAddOpen, setIsAddOpen] = useState(false);
    const [addImage, setAddImage] = useState('');
    const [addVideo, setAddVideo] = useState('');
    //拿数据   
    useEffect(() => {
        getMaterial({ type: type, currentPage: currentPage, pageSize: pageSize })
            .then(res => {
                console.log(res);
                setData(res.pageList);
                setTotal(res.total);
            })
    }, [type, currentPage, pageSize])
    // 修改封面图片
    const props = {
        name: 'file',
        action: 'http://localhost:1234/material/edit/image?id=' + msg.id,
        headers: {
            authorization: 'authorization-text',
        },
        onChange(info) {
            console.log(info);
            if (info.file.status !== 'uploading') {
                console.log(info.file.response);
                setMsg({ ...msg, perface: info.file.response.perface })
            }
            if (info.file.status === 'done') {

                // message.success(`${info.file.name} file uploaded successfully`);
            } else if (info.file.status === 'error') {
                // message.error(`${info.file.name} file upload failed.`);
            }
        },
    };

    // 添加封面
    const addProps = {
        name: 'file',
        action: 'http://localhost:1234/material/add/image',
        headers: {
            authorization: 'authorization-text',
        },
        onChange(info) {
            if (info.file.status !== 'uploading') {
                console.log(info.file.response);
                setAddImage(info.file.response);
            }
            if (info.file.status === 'done') {

                // message.success(`${info.file.name} file uploaded successfully`);
            } else if (info.file.status === 'error') {
                // message.error(`${info.file.name} file upload failed.`);
            }
        },
    };

    // 添加视频/图片
    const videoProps = {
        name: 'file',
        action: 'http://localhost:1234/material/add/video',
        headers: {
            authorization: 'authorization-text',
        },
        onChange(info) {
            if (info.file.status !== 'uploading') {
                console.log(info.file.response);
                setAddVideo(info.file.response);
            }
            if (info.file.status === 'done') {

                // message.success(`${info.file.name} file uploaded successfully`);
            } else if (info.file.status === 'error') {
                // message.error(`${info.file.name} file upload failed.`);
            }
        },
    };

    // 评论对话框
    const showModal = (record) => {
        console.log(record);
        setDefaultValue(record.outline);
        setIsModalOpen(true);
    };
    const handleCancel = () => {
        setIsModalOpen(false);
    };

    // 视频显示
    const showVideo = (record) => {
        setIsVideoOpen(true);
        setVideoMsg(record);
    }
    const videoCancel = () => {
        setIsVideoOpen(false);
    };

    // 编辑框
    const showEdit = (record) => {
        setIsEditOpen(true);
        setMsg(record);
    }
    const editCancel = () => {
        setIsEditOpen(false);
    };
    const onFinish = (values) => {
        console.log('Success:', values);
        editMaterial({ ...values, id: msg.id })
            .then(res => {
                // console.log(res);
                let list = data.map(item => {
                    if (item.id == msg.id) {
                        return item = res
                    }
                    else {
                        return item
                    }
                })
                // console.log(list);
                setData(list);

            })
        setIsEditOpen(false);
    };
    const onFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
    };

    // 删除数据
    const handleDelete = (id) => {
        delMaterial({ id })
            .then(res => {
                console.log(res);
            })
        const newData = data.filter((item) => item.id !== id);
        setData(newData);
    }

    // 添加数据
    const showAdd = () => {
        setIsAddOpen(true);
    }
    const addCancel = () => {
        setIsAddOpen(false);
    };
    const onAddFinish = (values) => {
        console.log('Success:', values);
        addMaterial({ ...values, image: addVideo, perface: addImage })
            .then(res => {
                setAddImage('');
                setAddVideo('');
                message.success("添加成功！");
            })
        setIsAddOpen(false);
    };
    const onAddFinishFailed = (errorInfo) => {
        console.log('Failed:', errorInfo);
        message.error("添加失败！");
    };

    // 查找
    const onSearch = (value) => {
        getSearch({ value, type, currentPage, pageSize })
            .then(res => {
                console.log(res);
                setData(res.searchList);
                setTotal(res.total);
            })
    }
    // 重置
    const onReset = () => {
        getMaterial({ type: type, currentPage: currentPage, pageSize: pageSize })
            .then(res => {
                console.log(res);
                setData(res.pageList);
                setTotal(res.total);
            })
    }
    // 分页
    const handleChange = (tag) => {
        setSelectedTag(tag.title);
        setType(tag.type)
        setCurrentPage(1);
    };

    const onChange = (page, pageSize) => {
        console.log(page, pageSize);
        setCurrentPage(page);
        setPageSize(pageSize);
    };

    // 表格
    const columns = [
        { title: '标题', dataIndex: 'name', align: 'center', width: 200 },
        {
            title: '梗概',
            dataIndex: 'outline',
            align: 'center',
            render: (_, record) => {
                return (
                    <a onClick={() => showModal(record)}>
                        点击查看
                    </a>
                )
            },
        },
        { title: '配音次数', dataIndex: 'voicenum', align: 'center', width: 100 },
        { title: '收藏量', dataIndex: 'starnum', align: 'center', width: 100 },
        {
            title: '图片/视频',
            dataIndex: 'image',
            align: 'center',
            width: 100,
            render: (_, record) => {
                return (
                    <div>
                        {
                            // console.log(record.image.includes('.mp4'))
                            record.image.includes('.mp4')
                                ?
                                <a onClick={() => showVideo(record)}>
                                    查看视频
                                </a>
                                :
                                <Image width={80} src={`http://localhost:1234/material/public/images/${record.image}`} />
                        }
                    </div>
                )
            }
        },
        {
            title: '封面',
            dataIndex: 'perface',
            align: 'center',
            width: 100,
            render: (_, record) => {
                return <Image width={80} src={`http://localhost:1234/material/public/images/${record.perface}`} />
            }

        },
        { title: '时间', dataIndex: 'date', align: 'center', width: 100 },
        {
            title: '操作',
            dataIndex: 'operation',
            align: 'center',
            width: 150,
            render: (_, record) => {
                return (
                    <div>
                        <Button type="primary"
                            size="small"
                            style={{ marginRight: "10px", backgroundColor: "#FEB955" }}
                            onClick={() => showEdit(record)}>
                            编辑
                        </Button>
                        <Popconfirm title="确定删除？" onConfirm={() => handleDelete(record.id)}>
                            <Button
                                type="primary"
                                size="small"
                                danger
                            // style={{ backgroundColor: '#D64E31' }}
                            >
                                删除
                            </Button>
                        </Popconfirm>
                    </div>
                )

            },
        },
    ];
    return (
        <div>
            <span
                style={{
                    marginRight: 8,
                }}
            >
            </span>
            <Space size={[0, 8]} wrap>
                {tagsData.map((tag) => (
                    <CheckableTag
                        key={tag.title}
                        checked={selectedTag.includes(tag.title)}
                        onChange={() => handleChange(tag)}
                    >
                        {tag.title}
                    </CheckableTag>
                ))}
            </Space>

            <div>
                <div
                    style={{
                        marginBottom: 16,
                        marginTop: 16
                    }}
                >
                    <div style={{ display: "inline-block", width: "100px" }} >
                        <Button
                            onClick={showAdd}
                            type="primary"
                        >
                            <PlusOutlined />新建
                        </Button>
                    </div>
                    <div className='search' style={{ display: "inline-block", float: "right" }}>
                        {/* <Input /> */}
                        <div style={{ display: "inline-block", position: "absolute", right: "110px" }}>
                            <Search placeholder="请输入您查询的信息" onSearch={onSearch} enterButton />
                        </div>
                        <Button
                            onClick={onReset}
                            type="primary"
                        >
                            重置
                        </Button>
                    </div>

                </div>
                <Form form={form} component={false}>
                    <Table
                        bordered
                        columns={columns}
                        dataSource={data}
                        pagination={{
                            current: currentPage,
                            onChange: onChange,
                            defaultCurrent: 1,
                            position: ['bottomCenter'],
                            total: total
                        }}
                    />
                </Form>
            </div>

            {/* 对话框 */}
            <>
                <Modal
                    title="素材梗概"
                    open={isModalOpen}
                    onCancel={handleCancel}
                    destroyOnClose={true}
                    footer={null}
                >
                    <Form
                        name="basic"
                        layout='vertical'
                        autoComplete="off"
                        preserve={false}
                    >
                        <Form.Item
                            name="outline"
                            initialValue={defaultValue}>
                            <TextArea rows={8} placeholder="请输入素材梗概" />
                        </Form.Item>
                    </Form>
                </Modal>
            </>
            {/* 视频框 */}
            <>
                <Modal
                    title={`${videoMsg.name}`}
                    open={isVideoOpen}
                    onCancel={videoCancel}
                    destroyOnClose={true}
                    footer={null}
                >
                    <Player>
                        <source src={`http://localhost:1234/material/public/video/${videoMsg.image}`} />
                    </Player>
                </Modal>
            </>
            {/* 编辑框 */}
            <>
                <Modal
                    open={isEditOpen}
                    title="修改信息"
                    onCancel={editCancel}
                    destroyOnClose={true}
                    footer={null}
                >
                    <Form
                        name="basic"
                        layout='vertical'
                        style={{
                            maxWidth: 400,
                            margin: '50px auto'
                        }}
                        initialValues={msg}
                        onFinish={onFinish}
                        onFinishFailed={onFinishFailed}
                        autoComplete="off"
                    >
                        <Form.Item
                            label="标题"
                            name="name"
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            label="梗概"
                            name="outline"

                        >
                            <TextArea rows={8} placeholder="请输入素材梗概" />
                        </Form.Item>
                        <Form.Item
                            label="配音次数"
                            name="voicenum"
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="收藏量"
                            name="starnum"
                        >
                            <Input />
                        </Form.Item>

                        <div>封面</div>
                        <div style={{ display: "inline-block", marginRight: "30px", marginBottom: "30px" }}>
                            <Image width={200} src={`http://localhost:1234/material/public/images/${msg.perface}`} />
                        </div>
                        <Upload {...props}>
                            <Button icon={<UploadOutlined />}>修改封面</Button>
                        </Upload>
                        <Form.Item
                            wrapperCol={{
                                offset: 10,
                                span: 24,
                            }}
                        >
                            <Button type="primary" htmlType="submit">
                                提交
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>
            </>
            {/* 新建框 */}
            <>
                <Modal
                    open={isAddOpen}
                    title="新建数据"
                    onCancel={addCancel}
                    destroyOnClose={true}
                    footer={null}
                >
                    <Form
                        name="basic"
                        layout='vertical'
                        style={{
                            maxWidth: 400,
                            margin: '50px auto'
                        }}
                        // initialValues={msg}
                        onFinish={onAddFinish}
                        onFinishFailed={onAddFinishFailed}
                        autoComplete="off"
                    >
                        <Form.Item
                            label="标题"
                            name="name"
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            label="类型"
                            name="type"
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            label="梗概"
                            name="outline"
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                        >
                            <TextArea rows={8} placeholder="请输入素材梗概" />
                        </Form.Item>

                        <Form.Item
                            label="用户id"
                            name="userid"
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item
                            label="配音次数"
                            name="voicenum"
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="收藏量"
                            name="starnum"
                            rules={[
                                {
                                    required: true,
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>

                        <div>视频/图片</div>
                        {
                            addVideo ?
                                <div style={{ display: "inline-block", marginRight: "30px", marginBottom: "30px" }}>
                                    {
                                        addVideo.includes('.mp4')
                                            ?
                                            <div style={{ display: "inline-block", width: "250px" }}>
                                                <Player width={200}>
                                                    <source src={`http://localhost:1234/material/public/video/${addVideo}`} />
                                                </Player>
                                            </div>
                                            :
                                            <Image width={200} src={`http://localhost:1234/material/public/images/${addVideo}`} />
                                    }
                                </div> :
                                ''
                        }
                        <Upload {...videoProps}>
                            <Button icon={<UploadOutlined />}>上传视频/图片</Button>
                        </Upload>

                        <div>封面</div>
                        {
                            addImage ?
                                <div style={{ display: "inline-block", marginRight: "30px", marginBottom: "30px" }}>
                                    <Image width={200} src={`http://localhost:1234/material/public/images/${addImage}`} />
                                </div> :
                                ''
                        }
                        <Upload {...addProps}>
                            <Button icon={<UploadOutlined />}>上传封面</Button>
                        </Upload>
                        <Form.Item
                            wrapperCol={{
                                offset: 10,
                                span: 24,
                            }}
                        >
                            <Button type="primary" htmlType="submit">
                                添加
                            </Button>
                        </Form.Item>
                    </Form>
                </Modal>
            </>
        </div >
    )
}

export default Material;